package com.zuoyue.myhttprequest;

import android.content.Context;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    public static final String BASE_URL = "https://www.icodingzy.xyz/android-system/user";

    public static void sendRequest(Context context, String url, RequestBody body) {
        Request request = null;
        if (body == null) {
            request = new Request.Builder()
                    .url(BASE_URL+ url)
                    .get()
                    .build();
        }else{
            request = new Request.Builder()
                    .post(body)
                    .url(BASE_URL + url)
                    .build();
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("请求发生错误", "onFailure: " + e.getMessage() );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                EventBus.getDefault().post(response.body().string());
            }
        });

    }
}
